<template>
  <div class="flow-direction-container">
    <div class="table-top-container">
      <el-row>
        <el-col :span="10">
          <el-button
            v-auth="{v: ['crm:baseInfo:contractedDistributor:service:create']}"
            class="border-btn"
            size="mini"
            @click="create"
          >新建配送服务</el-button>
          <!-- <el-button
            class="border-btn"
            size="mini"
            :disabled="selectionList.length===0"
          >批量提交审核</el-button> -->
        </el-col>
        <el-col :span="14">
          <div style="display: flex; justify-content: flex-end">
            <el-form
              :model="filterData"
              label-position="right"
              size="small"
              class="filter-form-inline"
            >
              <el-row
                :gutter="40"
                style="margin-left: 0px; margin-right: 0px"
              >
                <el-form-item
                  label="产品"
                  style="width:300px;margin-right:20px;"
                >
                  <el-select
                    v-model="filterData.productId"
                    style="width: 100%;"
                    clearable
                    filterable
                    remote
                    reserve-keyword
                    :remote-method="proRemoteMethod"
                    :loading="proLoading"
                    value-key="id"
                    placeholder="请选择产品"
                    @change="refreshList"
                  >
                    <el-option
                      v-for="item in productOptions"
                      :key="item.id"
                      :label="getProductName(item)"
                      :value="item.id"
                    >
                      <div class="pro-item">
                        <span>{{ getProductName(item) }}</span>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <filter-popover
                    right="20px"
                    :form-list="formList"
                    @onConfirm="filterDataConfirm"
                    @onReset="filterReset"
                  />
                </el-form-item>
              </el-row>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="table-list">
      <el-table
        :data="listData"
        header-cell-class-name="table-header"
        border
        style="width: 100%"
        :cell-style="cellStyle"
        @row-click="rowClick"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <!-- <el-table-column
          type="selection"
          width="55"
          header-align="center"
          align="center"
          :selectable="isSelectRow"
        /> -->
        <el-table-column
          v-if="checkListData.indexOf('distributeServeNo') !==-1"
          prop="distributeServeNo"
          label="流水号"
          :width="140"
          show-overflow-tooltip
          header-align="center"
          align="center"
          fixed="left"
        />
        <el-table-column
          v-if="checkListData.indexOf('region') !==-1"
          prop="region"
          label="配送地区"
          :min-width="160"
          show-overflow-tooltip
          header-align="center"
          fixed="left"
        >
          <template #default="scope">
            <div>
              <area-list-view :areas="scope.row.region" />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('productName') !==-1"
          label="商品名"
          prop="productName"
          :min-width="120"
          show-overflow-tooltip
          header-align="center"
        >
          <template #default="scope">
            <my-link>{{ scope.row.productName }}</my-link>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('productPopularName') !==-1"
          label="通用名"
          prop="productPopularName"
          :min-width="200"
          show-overflow-tooltip
          header-align="center"
        >
          <template #default="scope">
            <my-link>{{ scope.row.productPopularName }}</my-link>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('packSpecs') !==-1"
          prop="packSpecs"
          label="包装规格"
          :min-width="120"
          show-overflow-tooltip
          header-align="center"
        >
          <template #default="scope">
            <span>{{ scope.row.packSpecs }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('producer') !==-1"
          prop="producer"
          label="生产厂家"
          :min-width="140"
          show-overflow-tooltip
          header-align="center"
        />
        <el-table-column
          v-if="checkListData.indexOf('psf') !==-1"
          prop="psf"
          label="配送费"
          header-align="center"
          :min-width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div
              class="distribute-price-container"
              style="line-height: 20px;"
            >
              <div
                class="distribute-price-container"
                style="display:flex;"
              >
                <div
                  class="distributePrice"
                  style="max-width:75%;display:flex;align-items:center"
                >
                  <div
                    v-if="scope.row.computeMode==='固定价格'"
                    class="text-line-1"
                  >
                    <span>{{ scope.row.distributePrice }}元</span><span> / {{ getLabel('sell_unit',scope.row.sellUnit) }}</span>
                  </div>
                  <div
                    v-if="scope.row.computeMode==='终端价百分比'"
                    class="text-line-1"
                  >
                    <span>{{ scope.row.distributePrice }}%</span><span>终端价</span>
                  </div>
                </div>
                <div
                  v-if="scope.row.disStatus==='2'"
                  class="change-price-btn"
                  style="width:25%"
                >
                  <el-button
                    v-auth="{v: ['crm:baseInfo:contractedDistributor:service:changePrice'], bool: scope.row.disStatus === '2'&&!(scope.row.processDefinitionKey==='setDistributeServeUpdatePriceCheck'&&scope.row.flowStatus==='DOING')}"
                    type="text"
                    @click="changeDeliveryPrice(scope.row)"
                  >
                    <template #default>
                      <div>
                        <i class="iconfont icon-bianji" />
                      </div>
                    </template>
                  </el-button>
                </div>
              </div>
              <div
                v-if="scope.row.processDefinitionKey==='setDistributeServeUpdatePriceCheck'"
                class="distribute-price-status"
              >
                <div
                  v-if="scope.row.flowStatus==='DOING'||scope.row.flowStatus==='REJECT_INITIATOR'"
                  class="status flow-status-color"
                >
                  [ 变更审核中 ]
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('contractNumber') !==-1"
          prop="contractNumber"
          label="关联配送合同"
          :min-width="120"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <my-link
              v-if="scope.row.contractNumber"
              :underline="false"
            >{{ scope.row.contractNumber }}</my-link>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('expireTime') !==-1"
          prop="expireTime"
          label="服务结束日期"
          :min-width="140"
          show-overflow-tooltip
          header-align="center"
          align="center"
          sortable
        >
          <template #default="scope">
            <span>{{ dateFormat('yyyy-mm-dd', scope.row.expireTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('createdAt') !==-1"
          prop="createdAt"
          label="创建时间"
          :min-width="140"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <span>{{ dateFormat('yyyy-mm-dd HH:MM', scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('disStatus') !==-1"
          prop="disStatus"
          label="状态"
          :min-width="120"
          show-overflow-tooltip
          header-align="center"
          align="center"
          fixed="right"
        >
          <template #default="scope">
            <div
              class="status-contain"
              style="line-height: 20px"
            >
              <div class="status">{{ getLabel('distribute_server_status',scope.row.disStatus) }}</div>
              <div
                v-if="scope.row.disStatus === '1'"
                class="flow-status"
              >
                <div
                  v-if="scope.row.flowStatus==='REJECT_INITIATOR'"
                  class="flow-status-color"
                >[ {{ getLabel('approval_result', scope.row.flowStatus) }} ]</div>
              </div>
              <div
                v-if="scope.row.disStatus === '2'"
                class="flow-status"
              >
                <div
                  v-if="scope.row.processDefinitionKey==='setDistributeServeAssociationCheck'&&scope.row.flowStatus==='DOING'"
                  class="terminal-audit flow-status-color"
                >
                  [ 配送服务关联终端审核中 ]
                </div>
                <div
                  v-if="scope.row.processDefinitionKey==='setDistributeServeInvalidateCheck'&&scope.row.flowStatus==='DOING'"
                  class="flow-status-color"
                >[ 作废审核中 ]</div>
                <div
                  v-else-if="scope.row.isDistributeTerminal"
                  class="flow-status-color"
                >[ 无配送终端 ]</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          header-align="center"
          :width="240"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              v-auth="{v: ['crm:baseInfo:contractedDistributor:service:edit'], bool: scope.row.disStatus === '-1'||scope.row.processDefinitionKey==='setDistributeServeCreateCheck'&&scope.row.flowStatus==='REJECT_INITIATOR'}"
              type="text"
              @click="editService(scope.row, 'edit')"
            >编辑</el-button>
            <el-button
              v-auth="{v: ['crm:baseInfo:contractedDistributor:service:change'], bool: scope.row.disStatus === '2'}"
              type="text"
              @click="editService(scope.row, 'changeInfo')"
            >变更信息</el-button>
            <!--
              <el-button
                v-if="scope.row.disStatus === '2'"
                type="text"
                @click="relevanceTerminal(scope.row)"
              >关联配送终端</el-button>
            -->
            <!--有效并且不是审核中-->
            <el-button
              v-auth="{v: ['crm:baseInfo:contractedDistributor:service:zuofei'], bool: (scope.row.disStatus === '2'&&!(scope.row.processDefinitionKey==='setDistributeServeUpdatePriceCheck'&&scope.row.flowStatus==='DOING'||scope.row.processDefinitionKey==='setDistributeServeInvalidateCheck'&&scope.row.flowStatus==='DOING'))&&scope.row.isDistributeTerminal}"
              type="text"
              @click="obsoleteService(scope.row)"
            >作废</el-button>
            <el-button
              v-auth="{v: ['crm:baseInfo:contractedDistributor:service:delete'], bool: scope.row.disStatus === '-1'||scope.row.disStatus === '4'}"
              class="danger"
              type="text"
              @click="deleteService(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-model:page="filterData.page"
        v-model:limit="filterData.pageSize"
        style="display: flex; justify-content: flex-end"
        :total="total"
        @pagination="refreshList"
      />
    </div>
    <!-- 新建配送服务 -->
    <create-service
      ref="createServiceRef"
      @onsuccess="refreshList"
    />
    <!-- 变更配送费 -->
    <change-delivery-price
      ref="changePriceRef"
      @onsuccess="refreshList"
    />
    <!-- 关联配送终端 -->
    <associated-terminal ref="terminalRef" />
    <!-- 作废配送服务 -->
    <obsolete-service
      ref="obsoleteRef"
      @onsuccess="refreshList"
    />
    <!-- 配送服务详情 -->
    <detail-drawer
      ref="detailDrawer"
      custom-title
    >
      <template #title>
        <div
          class="draw-title"
          style="display:flex;justify-content:space-between;"
        >
          <div class="title-left">
            <span>配送服务详情 - {{ rowData.distributeServeNo }}</span>
            <service-status
              style="margin-left:4px"
              :datas="rowData"
            />
          </div>
          <div class="title-right">
            <el-button
              v-if="rowData.disStatus === '-1'"
              type="primary"
              size="small"
              @click="editService(rowData, 'edit')"
            >编辑</el-button>
            <el-button
              v-if="rowData.disStatus === '2'"
              type="primary"
              size="small"
              @click="editService(rowData, 'changeInfo')"
            >变更信息</el-button>
            <!--
              <el-button
                v-if="rowData.disStatus === '2'"
                type="primary"
                size="small"
                @click="relevanceTerminal(rowData)"
              >关联配送终端</el-button>
            -->
            <el-button
              v-if="(rowData.disStatus === '2'&&!(rowData.processDefinitionKey==='setDistributeServeUpdatePriceCheck'&&rowData.flowStatus==='DOING'||rowData.processDefinitionKey==='setDistributeServeInvalidateCheck'&&rowData.flowStatus==='DOING'))&&rowData.isDistributeTerminal"
              type="primary"
              size="small"
              @click="obsoleteService(rowData)"
            >作废</el-button>
            <el-button
              v-if="rowData.disStatus === '-1'||rowData.disStatus === '4'"
              class="danger"
              type="primary"
              size="small"
              @click="deleteService(rowData)"
            >删除</el-button>
          </div>
        </div>
      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <item-title title="基本信息" />
            <delivery-service-base-info
              v-model:refresh="refresh"
              :delivery-service-id="rowData?.id"
              @change-price="changeDeliveryPrice"
            />
          </div>
          <div class="history-list">
            <item-title title="操作记录" />
            <operation-view
              :id="rowData?.id"
              mode="distribute_serve"
            />
          </div>
        </div>
      </template>
    </detail-drawer>
    <!-- 产品详情 -->
    <detail-drawer
      ref="proDetailDrawer"
      custom-title
    >
      <template #title>
        <span>产品详情 {{ getProductName(rowData) }}</span>
      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <item-title title="基本信息" />
            <product-base-info
              v-if="rowData.productId"
              :id="rowData.productId"
            />
          </div>
          <div class="history-list">
            <item-title title="操作记录" />
            <operation-view
              v-if="rowData.productId"
              :id="rowData.productId"
              mode="product"
            />
          </div>
        </div>
      </template>
    </detail-drawer>
    <!--合同详情-->
    <detail-drawer
      ref="contractDrawer"
      custom-title
    >
      <template #title>
        <span>合同 {{ rowData?.contractName }} </span>
      </template>
      <template
        v-if="rowData?.contractId"
        #contents
      >
        <div class="drawer-content">
          <div class="history-list">
            <contract-detail
              ref="salesDetailDrawer"
              :contract-id="rowData?.contractId"
            />
          </div>
        </div>
      </template>
    </detail-drawer>
  </div>
</template>

<script>
import {
  defineAsyncComponent,
  defineComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  ref,
  toRefs,
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { crmStore } from '@CRM/store'

export default defineComponent({
  components: {
    createService: defineAsyncComponent(() =>
      import('./modules/createService.vue')
    ),
    deliveryServiceBaseInfo: defineAsyncComponent(() =>
      import('./modules/deliveryServiceBaseInfo.vue')
    ),
    associatedTerminal: defineAsyncComponent(() =>
      import('./modules/associatedTerminal.vue')
    ),
    obsoleteService: defineAsyncComponent(() =>
      import('./modules/obsoleteService.vue')
    ),
    changeDeliveryPrice: defineAsyncComponent(() =>
      import('./modules/changeDeliveryPrice.vue')
    ),
    serviceStatus: defineAsyncComponent(() =>
      import('./modules/serviceStatus.vue')
    ),
    productBaseInfo: defineAsyncComponent(() =>
      import(
        '@CRM/views/commonView/detailComponents/product/productBaseInfo.vue'
      )
    ),
    contractDetail: defineAsyncComponent(() =>
      import('@CRM/views/commonView/contract/contractDetail.vue')
    ),
  },
  props: {
    detail: {
      type: Object,
      default: () => {},
    },
  },
  setup(props, context) {
    const api = inject('api')
    const router = useRouter()
    const route = useRoute()
    const currentInstance = getCurrentInstance()
    var createServiceRef = ref(null)
    var terminalRef = ref(null)
    var obsoleteRef = ref(null)
    var changePriceRef = ref(null)
    var detailDrawer = ref(null)
    var proDetailDrawer = ref(null)
    var contractDrawer = ref(null)
    var reactiveData = reactive({
      total: 0,
      filterData: {
        distributeId: Number(route.query.id) || 0,
        productId: '',
        disStatus: '',
        startTime: null,
        endTime: null,
        serverStartTime: null,
        serverEndTime: null,
        reContract: '',
        region: [],
        sort: '',
        page: 1,
        pageSize: 20,
      },
      distributorDetail: props.detail,
      contractId: 0,
      rowData: null,
      refresh: false,
      checkListData: [
        'distributeServeNo',
        'region',
        'productName',
        'productPopularName',
        'producer',
        'packSpecs',
        'psf',
        'contractNumber',
        'expireTime',
        'createdAt',
        'czsj',
        'disStatus',
      ],
      tableOption: [
        {
          key: 'distributeServeNo',
          value: '流水号',
        },
        {
          key: 'region',
          value: '配送地区',
        },
        {
          key: 'productPopularName',
          value: '产品名称',
        },
        {
          key: 'producer',
          value: '生产厂家',
        },
        {
          key: 'packSpecs',
          value: '包装规格',
        },
        {
          key: 'psf',
          value: '配送费',
        },
        {
          key: 'contractNumber',
          value: '关联配送合同',
        },
        {
          key: 'expireTime',
          value: '服务结束日期',
        },
        {
          key: 'createdAt',
          value: '创建时间',
        },
        {
          key: 'disStatus',
          value: '状态',
        },
      ],
      listData: [],
      selectionList: [],
      proLoading: false,
      productOptions: [],
      formList: [
        {
          key: 'disStatus',
          label: '状态',
          form_type: 'select',
          value: '',
          is_search: false,
          options:
            crmStore.getters['dictionary/getDictionary'][
              'distribute_server_status'
            ],
        },
        // {
        //   key: 'area',
        //   label: '配送地区',
        //   form_type: 'cascader',
        //   value: [],
        //   is_search: false,
        //   multiple: true,
        //   checkStrictly: true,
        //   options: [],
        // },
        {
          key: 'serverEndRange',
          label: '服务结束时间',
          form_type: 'daterange',
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: 'createDateRange',
          label: '创建时间',
          form_type: 'daterange',
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: 'reContract',
          label: '关联合同',
          form_type: 'text',
          value: '',
          is_search: false,
          options: [],
        },
      ],
    })
    const checkList = (checked) => {
      reactiveData.checkListData = checked
    }
    const handleSelectionChange = (val) => {
      reactiveData.selectionList = val
    }
    const create = () => {
      createServiceRef.value.open('create', {
        serviceData: null,
        distributorDetail: reactiveData.distributorDetail,
      })
    }
    const editService = (row, type) => {
      createServiceRef.value.open(type, {
        serviceData: row,
        distributorDetail: reactiveData.distributorDetail,
      })
    }
    // 关联配送终端
    const relevanceTerminal = (row) => {
      terminalRef.value.open(row)
    }
    // 变更配送费
    const changeDeliveryPrice = (row) => {
      changePriceRef.value.open(row)
    }
    const obsoleteService = (row) => {
      obsoleteRef.value.open(row)
    }
    // 删除配送服务
    const deleteService = (row) => {
      currentInstance.proxy
        .alertBox({
          title: '配送服务删除',
          message: '数据删除后不可恢复，确定删除？',
        })
        .then(() => {
          api.distributors
            .DISTRIBUTORS_SERVICE_DELETE({ id: row.id })
            .then((res) => {
              if (res.code === 0) {
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '删除成功',
                })
                getList()
              } else {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: res.msg,
                })
              }
            })
        })
    }
    // 改数据是否可以选择
    const isSelectRow = (row, index) => {
      var bool = false
      if (row.disStatus === '1') {
        bool = true
      }
      return bool
    }
    const cellStyle = (row) => {
      if (
        row.column.label === '操作' ||
        row.column.label === '配送费' ||
        row.column.label === '关联配送合同'
      ) {
        return
      }
      return 'cursor: pointer;'
    }
    const rowClick = (row, column, event) => {
      console.log(row, column.label, event)
      if (column.label === '配送费' || column.label === '操作') return

      reactiveData.rowData = row

      if (column.label === '商品名' || column.label === '通用名') {
        proDetailDrawer.value.open()
      } else if (column.label === '关联配送合同') {
        console.log('关联配送合同')
        if (row.contractId) {
          contractDrawer.value.open()
        } else {
          currentInstance.proxy.customMessage({
            type: 'warning',
            message: '无关联合同',
          })
        }
      } else {
        detailDrawer.value.open()
      }
    }
    const getList = () => {
      api.distributors
        .DISTRIBUTORS_SERVICE_LIST(reactiveData.filterData)
        .then((res) => {
          if (res.code === 0) {
            reactiveData.listData = res.data.list || []
            reactiveData.total = res.data.total
            // 判断如果在抽屉操作，更新rowData数据
            if (reactiveData.rowData) {
              console.log(reactiveData.rowData)
              var item = reactiveData.listData.find(
                (p) => p.id === reactiveData.rowData.id
              )
              if (item) {
                reactiveData.rowData = item
                reactiveData.refresh = true
                console.log(reactiveData.refresh)
              } else {
                reactiveData.rowData = null
                detailDrawer.value.close()
              }
            }
          }
        })
    }
    const sortChange = (column) => {
      console.log(column)
      if (column.prop === 'expireTime') {
        if (column.order === 'ascending') {
          reactiveData.filterData.sort = 'asc'
        } else if (column.order === 'descending') {
          reactiveData.filterData.sort = 'desc'
        }
      }
      refreshList()
    }
    const proRemoteMethod = async(query) => {
      if (query !== '') {
        reactiveData.proLoading = true
        var pro = await api.common.GET_PRODUCT_LIST({ keyWord: query })
        if (pro.code === 0) {
          reactiveData.productOptions = pro.data.list
        } else {
          reactiveData.productOptions = []
        }
        reactiveData.proLoading = false
      } else {
        reactiveData.productOptions = []
      }
    }
    const filterReset = () => {
      reactiveData.filterData = {
        distributeId: Number(route.query.id) || 0,
        productId: '',
        disStatus: '',
        startTime: null,
        endTime: null,
        serverStartTime: null,
        serverEndTime: null,
        reContract: '',
        region: [],
        sort: '',
        page: 1,
        pageSize: 20,
      }
      getList()
    }
    const filterDataConfirm = (formdata) => {
      reactiveData.filterData.disStatus = formdata.disStatus
      reactiveData.filterData.reContract = formdata.reContract
      reactiveData.filterData.startTime =
        formdata.createDateRange && formdata.createDateRange.length
          ? formdata.createDateRange[0]
          : null
      reactiveData.filterData.endTime =
        formdata.createDateRange && formdata.createDateRange.length
          ? formdata.createDateRange[1]
          : null
      reactiveData.filterData.serverStartTime =
        formdata.serverEndRange && formdata.serverEndRange.length
          ? formdata.serverEndRange[0]
          : null
      reactiveData.filterData.serverEndTime =
        formdata.serverEndRange && formdata.serverEndRange.length
          ? formdata.serverEndRange[1]
          : null
      // reactiveData.filterData.region =
      //   currentInstance.proxy.getCascaderAreaData(formdata.area)

      getList()
    }
    const refreshList = () => {
      getList()
    }
    onMounted(() => {
      getList()
    })

    return {
      ...toRefs(reactiveData),
      detailDrawer,
      proDetailDrawer,
      contractDrawer,
      createServiceRef,
      terminalRef,
      obsoleteRef,
      changePriceRef,
      checkList,
      handleSelectionChange,
      create,
      editService,
      refreshList,
      relevanceTerminal,
      deleteService,
      isSelectRow,
      cellStyle,
      rowClick,
      obsoleteService,
      changeDeliveryPrice,
      proRemoteMethod,
      filterReset,
      filterDataConfirm,
      sortChange,
    }
  },
})
</script>

